package conexion;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class Conexion {
	
	static long epoch = System.currentTimeMillis()/1000; //Tiempo Unix
	static String hash=""; //Hash de la respuesta secreta
	static String easf_sess_com; //Cookie 1
	static String EASW_KEY; //Cookie 2
	static String XUTSID; //Sid
	static String nucleusId; //NucleusId
	static String FUTWebPhishing; //Cookie 3
 
	public static void excutePost(String urlParameters){
		URL urlLogin;
		HttpsURLConnection connectionLogin = null;  
		try {
			//Conexion https://www.ea.com/es/futbol/services/authenticate/login (Generico para todas las plataformas)
			urlLogin = new URL("https://www.ea.com/es/futbol/services/authenticate/login"); //Web para el login con email y contraseña
			connectionLogin = (HttpsURLConnection)urlLogin.openConnection();
			connectionLogin.setRequestMethod("POST");
			connectionLogin.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); //Hacemos creer a EA que somos un navegador
			connectionLogin.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connectionLogin.setRequestProperty("Referer", "http://www.ea.com/es/futbol/login");
			connectionLogin.setRequestProperty("Content-Length", "" +Integer.toString(urlParameters.getBytes().length));
			connectionLogin.setRequestProperty("Content-Language", "es-ES");  
			connectionLogin.setUseCaches (false);connectionLogin.setDoInput(true);connectionLogin.setDoOutput(true);
			
			//Send request
			DataOutputStream wr = new DataOutputStream (connectionLogin.getOutputStream ());
			wr.writeBytes (urlParameters); //Parametros para iniciar sesion
			wr.flush ();
			wr.close ();
			
			//Get Response	
			InputStream is = connectionLogin.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			String [] extracLine;
			extracLine = new String[rd.toString().length()];
			int cont=0;
			
			while((line = rd.readLine()) != null) {
				//System.out.println(line);
				extracLine[cont] = line;
				cont++;
			}
			
			String nucleusIdXML=extracLine[4];
			String nucleusIdSubStr = nucleusIdXML.substring(nucleusIdXML.indexOf("<nucleusId>")+"<nucleusId>".length(),nucleusIdXML.length());
			nucleusId =nucleusIdSubStr.substring(nucleusIdSubStr.indexOf("") , nucleusIdSubStr.indexOf("<"));
			System.out.println("nucleusId: "+nucleusId);
			
			// Obtenemos la cabecera para extraer las cookies 1 y 2
			Map<String,List<String>> cm = connectionLogin.getHeaderFields();
			List<String> sc = cm.get("Set-Cookie");
			
			int lengthCookies = sc.size();
			for (int i=0; i<lengthCookies;i++){
				int index;
				String cookies = sc.get(i);
				if((index=cookies.indexOf("easf_sess_com=")) != -1){
					int index2 = cookies.indexOf(";", index);
					easf_sess_com = cookies.substring(index, index2);
					System.out.println("\n"+easf_sess_com); //Cookie 1
				}
				if((index=cookies.indexOf("EASW_KEY=")) != -1){
					int index2 = cookies.indexOf(";", index);
					EASW_KEY = cookies.substring(index, index2);
					System.out.println("\n"+EASW_KEY); //Cookie 2
				}
			}
			rd.close(); //Cerramos conexion con la URL
		}
		catch (Exception e) {e.printStackTrace();} 
		finally {if(connectionLogin != null) {connectionLogin.disconnect();}}
	}
	
	public static void timeStamp(){
		
		URL urlTimestamp;
		HttpURLConnection connectionTimestamp = null;  
		String setCookie = ""+EASW_KEY+"; "+easf_sess_com+"";
		
		try {
			//Conexion con http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/shards?timestamp="+epoch (Esta URL cambia segun que plataforma tenga el usuario: card-360, card-ps3, card-pc)
			urlTimestamp = new URL("http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/shards?timestamp="+epoch);
			connectionTimestamp = (HttpURLConnection)urlTimestamp.openConnection();
			connectionTimestamp.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); //Hacemos creer a EA que somos un navegador
			connectionTimestamp.setRequestProperty("Cookie", setCookie); //Enviamos la cookie 1 y cookie 2 para mantener la sesion abierta
			connectionTimestamp.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connectionTimestamp.setUseCaches (false);connectionTimestamp.setDoInput(true);connectionTimestamp.setDoOutput(true);
			
			//Get Response	
			InputStream isTimestamp = connectionTimestamp.getInputStream();
			BufferedReader rdTimestamp = new BufferedReader(new InputStreamReader(isTimestamp));
			String lineTimestamp;
			lineTimestamp = rdTimestamp.readLine();	
			//while((line = rdT.readLine()) != null) {
				//System.out.println("\n"+lineTimestamp);
			//}
			
			Map<String,List<String>> cmTimestamp = connectionTimestamp.getHeaderFields(); //Obtenemos la cabecera (De aqui no extraemos nada)
			
			rdTimestamp.close(); //Cerramos conexion con la URL
		}
		catch (Exception e) {e.printStackTrace();}
		finally {if(connectionTimestamp != null) {connectionTimestamp.disconnect();}}
	}

	public static void acount(){
		URL urlTimestamp;
		URL urlAuth;
		URL urlValidate;
		HttpURLConnection connectionTimestamp = null;
		HttpURLConnection connectionAuth = null;
		HttpURLConnection connectionValidate = null;
		String setCookie = ""+EASW_KEY+"; "+easf_sess_com+"";
		
		try {
			//Conexion con http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/shards?timestamp="+epoch (Esta URL cambia segun que plataforma tenga el usuario: card-360, card-ps3, card-pc)
			urlTimestamp = new URL("http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/game/fifa13/user/accountinfo?timestamp="+epoch);
			//Conexion con http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/auth (Esta URL cambia segun que plataforma tenga el usuario: card-360, card-ps3, card-pc)
			urlAuth = new URL("http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/auth");
			//Conexion con http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/game/fifa13/phishing/validate (Esta URL cambia segun que plataforma tenga el usuario: card-360, card-ps3, card-pc)
			urlValidate = new URL("http://www.ea.com/p/fut/a/card-360/l/es_ES/s/p/ut/game/fifa13/phishing/validate");

			connectionTimestamp = (HttpURLConnection)urlTimestamp.openConnection();
			connectionTimestamp.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); //Hacemos creer a EA que somos un navegador
			connectionTimestamp.setRequestProperty("Cookie", setCookie);  
			connectionTimestamp.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connectionTimestamp.setUseCaches (false);connectionTimestamp.setDoInput(true);connectionTimestamp.setDoOutput(true);
			
			//Get Response	
			InputStream isTimestamp = connectionTimestamp.getInputStream();
			BufferedReader rdTimestamp = new BufferedReader(new InputStreamReader(isTimestamp));
			String lineTimestamp;
			lineTimestamp = rdTimestamp.readLine();
			//while((line = rdTimestamp.readLine()) != null){
				//System.out.println("\n"+lineTimestamp);
			//}
			
			//Obtener datos para auntentificacion
			JSONObject json = (JSONObject)new JSONParser().parse(lineTimestamp);
			Object userAccountInfo =json.get("userAccountInfo");
								
			String line2 = userAccountInfo.toString();
			JSONObject json2 = (JSONObject)new JSONParser().parse(line2);
			Object personas =json2.get("personas");
								
			JSONArray array = (JSONArray)personas;
			Object objArray = array.get(0);
								
			String line3 = objArray.toString();
			JSONObject json3 = (JSONObject)new JSONParser().parse(line3);
			Object personaId =json3.get("personaId");
			Object personaName =json3.get("personaName");
			Object userClubList =json3.get("userClubList");
			System.out.println("\npersonaId: "+personaId);
			System.out.println("personaName: "+personaName);
								
			JSONArray array2 = (JSONArray)userClubList;
			Object objArray2 = array2.get(0);
								
			String line4 = objArray2.toString();
			JSONObject json4 = (JSONObject)new JSONParser().parse(line4);
			Object platform =json4.get("platform");
			Object badgeId =json4.get("badgeId");
			Object clubAbbr =json4.get("clubAbbr");
			Object clubName =json4.get("clubName");
			System.out.println("platform: "+platform);
			System.out.println("badgeId: "+badgeId);
			System.out.println("clubAbbr: "+clubAbbr);
			System.out.println("clubName: "+clubName);
			
			rdTimestamp.close();
			
			//Metodo para el Auth
			
			//String dataAuth  ="{ "isReadOnly": false, "sku": "393A0001", "clientVersion": 3, "nuc": 2290981029, "nucleusPersonaId": 202971851, "nucleusPersonaDisplayName": "Guti23", "nucleusPersonaPlatform": "360", "locale": "es-ES", "method": "idm", "priorityLevel":4, "identification": { "EASW-Token": "" } }
			String dataAuth  ="{ \"isReadOnly\": false, \"sku\": \"393A0001\", \"clientVersion\": 3, \"nuc\": "+ nucleusId+", \"nucleusPersonaId\": " +personaId+", \"nucleusPersonaDisplayName\": \""+personaName+"\", \"nucleusPersonaPlatform\": \""+platform+"\", \"locale\": \"es-ES\", \"method\": \"idm\", \"priorityLevel\":4, \"identification\": { \"EASW-Token\": \"\" } }";
			connectionAuth = (HttpURLConnection)urlAuth.openConnection();
			connectionAuth.setRequestMethod("POST");
			connectionAuth.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); //Hacemos creer a EA que somos un navegador
			connectionAuth.setRequestProperty("Cookie", setCookie);
			connectionAuth.setRequestProperty("Content-Type", "application/json");
			connectionAuth.setRequestProperty("Referer", "http://www.ea.com/es/futbol/fifa-ultimate-team");
			connectionAuth.setRequestProperty("Content-Length", "" +Integer.toString(dataAuth.getBytes().length));
			connectionAuth.setRequestProperty("Content-Language", "es-ES");  										
			connectionAuth.setUseCaches(false);connectionAuth.setDoInput(true);connectionAuth.setDoOutput(true);
			
			//Send request
			DataOutputStream wrAuth = new DataOutputStream (connectionAuth.getOutputStream ());
			wrAuth.writeBytes (dataAuth); //Enviamos los datos de autentificacion
			wrAuth.flush ();
			wrAuth.close ();
			
			//Get Response	
			InputStream isAuth = connectionAuth.getInputStream();
			BufferedReader rdAuth = new BufferedReader(new InputStreamReader(isAuth));
			String lineUrlAuth;
			lineUrlAuth = rdAuth.readLine();
//			while((lineUrlAuth = rdAuth.readLine()) != null) {
				//System.out.println(lineUrlAuth);
//			}
			
			//Obtenemos las cabeceras para extraer el SID
			Map<String,List<String>> cm = connectionAuth.getHeaderFields();
			List<String> sc = cm.get("X-UT-SID");
			
			//Extraemos el SID
			String XUTSIDA =sc.toString();
			String XUTSIDB = XUTSIDA.substring(XUTSIDA.indexOf("[")+"[".length(),XUTSIDA.length());
			XUTSID =XUTSIDB.substring(XUTSIDB.indexOf("") , XUTSIDB.indexOf("]"));
			System.out.println("\nX-UT-SID: "+XUTSID);
					
			rdAuth.close(); // Cerramos la conexion con la URL
			
			//Metodo para pregunta de segutirad
			String respuestaHash = "answer="+hash;
			
			connectionValidate = (HttpURLConnection)urlValidate.openConnection();
			connectionValidate.setRequestMethod("POST");
			connectionValidate.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); //Hacemos creer a EA que somos un navegador
			connectionValidate.setRequestProperty("Cookie", setCookie);
			connectionValidate.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connectionValidate.setRequestProperty("Referer", "http://www.ea.com/es/futbol/fifa-ultimate-team");
			connectionValidate.setRequestProperty("Content-Length", "" +Integer.toString(respuestaHash.getBytes().length));  
			connectionValidate.setRequestProperty("Content-Language", "es-ES");
			connectionValidate.setRequestProperty("X-Ut-Sid", XUTSID);
			connectionValidate.setRequestProperty("X-Requested-With", "XMLHttpRequest");
			connectionValidate.setRequestProperty("X-Ut-Embed-Error", "true");
			connectionValidate.setUseCaches (false);connectionValidate.setDoInput(true);connectionValidate.setDoOutput(true);
			
			//Send request
			DataOutputStream wrValidate = new DataOutputStream (connectionValidate.getOutputStream ());
			wrValidate.writeBytes (respuestaHash); //Enviamos la respuesta secreta hasheada
			wrValidate.flush ();
			wrValidate.close ();
			
			//Get Response	
			InputStream isValidate = connectionValidate.getInputStream();
			BufferedReader rdValidate = new BufferedReader(new InputStreamReader(isValidate));
			String lineUrlValidate;
			lineUrlValidate = rdValidate.readLine();
			//while((lineUrlValidate = rdValidate.readLine()) != null) {
				//System.out.println("\n"+lineUrlValidate);
			//}
			 
			//Obtenemos las cabeceras para estraer el FUTWebPhisiongKey
			Map<String,List<String>> cmValidate = connectionValidate.getHeaderFields();
			List<String> scValidate = cmValidate.get("Set-Cookie");

			//Extraemos la Phising Key
			String FUTWebPhishingA =scValidate.toString();
			String FUTWebPhishingB = FUTWebPhishingA.substring(FUTWebPhishingA.indexOf("FUTWebPhishing")+"FUTWebPhishing".length(),FUTWebPhishingA.length());
			FUTWebPhishing =FUTWebPhishingB.substring(FUTWebPhishingB.indexOf("") , FUTWebPhishingB.indexOf(";"));
			System.out.println("\nFUTWebPhishing"+FUTWebPhishing);
			
			rdValidate.close(); //Cerramos conexion con la URL
		} 
		catch (Exception e) {e.printStackTrace();}
	}
	
	public static int monedas(){
		URL urlUser;
		HttpsURLConnection connectionMonedas = null;
		String setCookie = EASW_KEY + "; " + easf_sess_com + "; FUTWebPhishing" + FUTWebPhishing;
		String monedas = null;
		int credits=0;
		try{				
			//Conexion con https://utas.fut.ea.com/ut/game/fifa13/user/credits (En Xbox y en IOs: https://utas.fut.ea.com, en Ps3 y Pc: https://utas.s2.fut.ea.com)
			urlUser = new URL("https://utas.fut.ea.com/ut/game/fifa13/user/credits");		
			connectionMonedas = (HttpsURLConnection)urlUser.openConnection();		
			connectionMonedas.setRequestMethod("POST");		
			connectionMonedas.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); //Hacemos creer a EA que somos un navegador
			connectionMonedas.setRequestProperty("Cookie", setCookie); //Enviamos las 3 cookies
			connectionMonedas.setRequestProperty("Content-Type", "application/json");		
			connectionMonedas.setRequestProperty("X-UT-SID", XUTSID);		
			connectionMonedas.setRequestProperty("X-HTTP-Method-Override", "GET"); 		
			connectionMonedas.setUseCaches (false);connectionMonedas.setDoInput(true);connectionMonedas.setDoOutput(true);		

			//Get Response	
			InputStream isMonedas = connectionMonedas.getInputStream();	
			BufferedReader rdMonedas = new BufferedReader(new InputStreamReader(isMonedas));		
			String lineMonedas;		
			lineMonedas = rdMonedas.readLine();
			lineMonedas = lineMonedas.substring(lineMonedas.indexOf("credits")+"credits".length(),lineMonedas.length());
	    	
			monedas=lineMonedas.substring(lineMonedas.indexOf(":")+1 , lineMonedas.indexOf(","));
			credits = Integer.parseInt(monedas);
		
		}
		catch(Exception e){}
		
		return credits;
	}

}